//
//  DKPanCardPhotoView.m
//  DanKU
//
//  Created by 吴斌 on 2023/11/22.
//

#import "DKPanCardPhotoController.h"
#import <AVFoundation/AVFoundation.h>
#import "DKPanCardReTakeAlertView.h"
static NSString *NoCameraAccessAlertTitle = @"Unable to access the Camera";
static NSString *NoCameraAccessAlertMessage = @"To turn on camera access, choose Settings > Privacy > Camera and turn on Camera access for this app.";
@interface DKPanCardPhotoController()<AVCapturePhotoCaptureDelegate>
@property (nonatomic, strong)AVCaptureSession * captureSession;
@property (nonatomic, strong)AVCaptureDevice  * captureDevice;
@property (nonatomic, strong)AVCaptureDeviceInput * captureDeviceInput;
@property (nonatomic, strong)AVCapturePhotoOutput * photoOutput;
@property (nonatomic, strong)AVCaptureVideoPreviewLayer * previewLayer;
@property (nonatomic, strong)AVCapturePhotoSettings * photoSettings;
@property (nonatomic, assign)AVCaptureDevicePosition  position;

@property (nonatomic, strong)UIButton * dk_photoBtn;
@property (nonatomic, strong)UIImageView * dk_photoImgView;
@property (nonatomic,strong) UIView *dk_photoAlertView;
@end
@implementation DKPanCardPhotoController
-(AVCaptureSession *)captureSession{
    if(!_captureSession){
        _captureSession = [[AVCaptureSession alloc] init];
        if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
            _captureSession.sessionPreset = AVCaptureSessionPreset1280x720;
        }
    }
    return _captureSession;
}
-(AVCaptureDevice *)captureDevice{
    if(!_captureDevice){
        _captureDevice = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInWideAngleCamera mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionBack];
    }
    return _captureDevice;
}
-(AVCaptureDeviceInput *)captureDeviceInput{
    if(!_captureDeviceInput){
        _captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:self.captureDevice error:nil];
    }
    return _captureDeviceInput;
}
-(AVCapturePhotoOutput *)photoOutput{
    if(!_photoOutput){
        _photoOutput = [[AVCapturePhotoOutput alloc] init];
    }
    return _photoOutput;
}
-(AVCaptureVideoPreviewLayer *)previewLayer{
    if(!_previewLayer){
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
        _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        _previewLayer.frame = self.view.bounds;
    }
    return _previewLayer;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = DK_HexA(@"#000000", 1.0);
    [self makePhotoSize];
    [self makeFunView];
    // 检查授权
    WeakSelf(self)
    [self checkCameraAccessWithBlock:^(BOOL cameraAvailable) {
        // 相机不可用
        if (!cameraAvailable) {
            
        }else{
            [weakSelf.view.layer insertSublayer:weakSelf.previewLayer atIndex:0];
            if([weakSelf.captureSession canAddInput:weakSelf.captureDeviceInput]){
                [weakSelf.captureSession addInput:weakSelf.captureDeviceInput];
            }
            if([weakSelf.captureSession canAddOutput:weakSelf.photoOutput]){
                [weakSelf.captureSession addOutput:weakSelf.photoOutput];
            }
            [weakSelf startRunning];
        }
    }];
}
- (void)makeDragBtn{

}
- (void)makeFunView{
    UIButton * dk_backBtn = [[UIButton alloc] init];
    [dk_backBtn setBackgroundImage:DK_GetImage(@"dk_AuthCardBack") forState:UIControlStateNormal];
    [dk_backBtn addTarget:self action:@selector(panPhotoBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:dk_backBtn];
    [dk_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(DK_IsWidthScale(11)+DK_SafeAreaTop));
        make.left.equalTo(@(DK_IsWidthScale(41)));
        make.height.equalTo(@(DK_IsWidthScale(18)));
        make.width.equalTo(@(DK_IsWidthScale(17)));
    }];
    UILabel * dk_AuthCardTitleLab = [[UILabel alloc] init];
    dk_AuthCardTitleLab.textColor = DK_Hex(@"#FFFFFF");
    dk_AuthCardTitleLab.text = @"PAN Card";
    dk_AuthCardTitleLab.font = DK_FONT_Medium(16);
    [self.view addSubview:dk_AuthCardTitleLab];
    [dk_AuthCardTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(dk_backBtn);
        make.centerX.equalTo(self.view);
        make.top.equalTo(@(DK_IsWidthScale(18)));
        make.height.equalTo(@(DK_IsWidthScale(22)));
    }];
    self.dk_photoBtn = [[UIButton alloc] init];
    [self.dk_photoBtn setBackgroundImage:DK_GetImage(@"dk_AuthCardPhotoSelect") forState:UIControlStateNormal];
    [self.dk_photoBtn setBackgroundImage:DK_GetImage(@"dk_AuthCardPhotoNor") forState:UIControlStateDisabled];
    [self.dk_photoBtn addTarget:self action:@selector(startCamera) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.dk_photoBtn];
    [self.dk_photoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@(-DK_IsWidthScale(54)-DK_SafeAreaBottom));
        make.centerX.equalTo(self.view);
        make.height.equalTo(@(DK_IsWidthScale(70)));
        make.width.equalTo(@(DK_IsWidthScale(70)));
    }];
    self.dk_photoImgView = [[UIImageView alloc] init];
    self.dk_photoImgView.layer.cornerRadius = 10;
    self.dk_photoImgView.clipsToBounds = YES;
    self.dk_photoImgView.userInteractionEnabled = YES;
    self.dk_photoImgView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:self.dk_photoImgView];
    [self.dk_photoImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.dk_photoBtn.mas_top).offset(-DK_IsWidthScale(70));
        make.width.equalTo(_dk_photoImgView.mas_height).dividedBy(426.0/273.0);
    }];
    UIImageView * dk_photoCenterImgView = [[UIImageView alloc] init];
    dk_photoCenterImgView.image = DK_GetImage(@"dk_AuthCardPhotoArea");
    dk_photoCenterImgView.userInteractionEnabled = YES;
    [self.view addSubview:dk_photoCenterImgView];
    [dk_photoCenterImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.dk_photoImgView);
        make.right.equalTo(self.dk_photoImgView);
        make.top.equalTo(self.dk_photoImgView);
        make.bottom.equalTo(self.dk_photoImgView);
    }];
    UILabel * dk_AuthCardFrameLab = [[UILabel alloc] init];
    dk_AuthCardFrameLab.textColor = DK_Hex(@"#FFFFFF");
    dk_AuthCardFrameLab.text = @"Please the card in the shooting frame";
    dk_AuthCardFrameLab.font = DK_FONT_Regular(13);
    dk_AuthCardFrameLab.transform = CGAffineTransformMakeRotation(M_PI/2);
    [self.view addSubview:dk_AuthCardFrameLab];
    [dk_AuthCardFrameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_left).offset(DK_IsWidthScale(33));
        make.centerY.equalTo(self.view);
        make.height.equalTo(@(DK_IsWidthScale(18)));
    }];
    self.dk_photoAlertView = [[UIView alloc] init];
    self.dk_photoAlertView.backgroundColor = UIColor.clearColor;
    self.dk_photoAlertView.transform = CGAffineTransformMakeRotation(M_PI/2);
    self.dk_photoAlertView.userInteractionEnabled = NO;
    [self.view addSubview:self.dk_photoAlertView];
    [self.dk_photoAlertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view);
        make.height.equalTo(@(DK_SCREEN_H));
        make.width.equalTo(@(DK_SCREEN_W));
    }];
}
//拍照区域大小
- (void)makePhotoSize{
    CAShapeLayer * cardShapeLayer = [CAShapeLayer layer];
    cardShapeLayer.position = self.view.layer.position;
    CGFloat height = (DK_SCREEN_H/2 - DK_IsWidthScale(54)-DK_SafeAreaBottom- DK_IsWidthScale(140))*2;
    CGFloat width = height/(426.0/273.0);
    cardShapeLayer.bounds = (CGRect){CGPointZero, {width, height}};
    cardShapeLayer.cornerRadius = 10;
    [self.view.layer addSublayer:cardShapeLayer];
    // 最里层镂空
    UIBezierPath *cardRectPath = [UIBezierPath bezierPathWithRoundedRect:cardShapeLayer.frame cornerRadius:cardShapeLayer.cornerRadius];
    
    // 最外层背景
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.view.frame];
    [path appendPath:cardRectPath];
    [path setUsesEvenOddFillRule:YES];
    
    CAShapeLayer *fillLayer = [CAShapeLayer layer];
    fillLayer.path = path.CGPath;
    fillLayer.fillRule = kCAFillRuleEvenOdd;
    fillLayer.fillColor = [UIColor blackColor].CGColor;
    fillLayer.opacity = 0.6;
    
    [self.view.layer addSublayer:fillLayer];
    
//    CGRect photoCenterRect = self.dk_photoImgView.frame;
//    CGRect rectOfInterest = [self.previewLayer metadataOutputRectOfInterestForRect:photoCenterRect];
//    [self.photoOutput metadataOutputRectOfInterestForRect:rectOfInterest];
}
- (void)panPhotoBack{
    [DKPublicHttp apiUserBrhavRecordForAPI:@{} withPageName:DK_VerifyIdentify withAction:DK_ActionID_Pan_Front_Cancel complete:^{
            
    } fail:^{
            
    }];
    [self dismissViewControllerAnimated:YES completion:^{
            
    }];
//    [self.navigationController popViewControllerAnimated:YES];
}
//开始运行
- (void)startRunning{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [self.captureSession startRunning];
    });
}
//停止运行
- (void)stopRunning{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [self.captureSession stopRunning];
    });
}
//拍照
- (void)startCamera{
    self.photoSettings = [AVCapturePhotoSettings photoSettingsWithFormat:@{AVVideoCodecKey:AVVideoCodecTypeJPEG}];
    if(!self.previewLayer||!self.photoOutput||!self.photoSettings){
        return;
    }
    if(self.captureSession.isRunning == YES){
        [self.photoOutput capturePhotoWithSettings:self.photoSettings delegate:self];
    }
}
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
    if(!error){
        NSData *imageData = [photo fileDataRepresentation];
        UIImage *image = [UIImage imageWithData:imageData];
        UIImage *fix = [self fixOrientation:image];
        UIImage *cut = [self cutImage:fix imageView:[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, fix.size.width, fix.size.height)]];
        self.dk_photoImgView.image = cut;
        self.dk_photoBtn.enabled = NO;
        [self makeUploadPan];
    }
}
- (void)closeCarema{
    [self dismissViewControllerAnimated:YES completion:^{
            
    }];
//    [self.navigationController popViewControllerAnimated:YES];
}
- (void)makeUploadPan{
    [DKPublicHttp apiUserBrhavRecordForAPI:@{} withPageName:DK_VerifyIdentify withAction:DK_ActionID_Pan_Front_Request complete:^{
            
    } fail:^{
            
    }];
    WeakSelf(self)
    UIImage *rotationImage = [UIImage imageWithCGImage:self.dk_photoImgView.image.CGImage scale:2.0 orientation:UIImageOrientationLeft];
    NSData *imageData = [NSString changeImageSizeForData:rotationImage toByte:300000];
    NSDictionary *parmDic = @{@"channel":@"DEFAULT"};
    [DKPublicHttp apiGetCommonPanPositiveForAPI:parmDic withData:imageData complete:^(DKAuthPanCardModel * _Nonnull dk_AuthPanCardMdl) {
        if(weakSelf.PanCardScuessBlock){
            weakSelf.PanCardScuessBlock(dk_AuthPanCardMdl);
        }
        weakSelf.dk_photoBtn.enabled = NO;
        [weakSelf closeCarema];
    } fail:^(NSString * _Nonnull msg) {
        [DKAlertHelper showPopupMessage:msg toView:self.dk_photoAlertView centerPoint:CGPointMake(self.dk_photoAlertView.center.x, self.dk_photoAlertView.center.y+DK_IsWidthScale(90))];
        weakSelf.dk_photoBtn.enabled = NO;
        [DKPanCardReTakeAlertView dk_ShowAuthPanCardReTakeAlertViewComplete:^{
            
        } withDissBlock:^{
            weakSelf.dk_photoImgView.image = nil;
            weakSelf.dk_photoBtn.enabled = YES;
        }];
    }];
}
#pragma mark - 图片处理
// 图片旋转
- (UIImage *)fixOrientation:(UIImage *)aImage
{
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
- (UIImage *)cutImage:(UIImage *)cutImage imageView:(UIImageView *)imageView{
    CGFloat cutImageheight = (DK_SCREEN_H/2 - DK_IsWidthScale(54)-DK_SafeAreaBottom- DK_IsWidthScale(140))*2;
    CGFloat cutImagewidth = cutImageheight/(426.0/273.0);
    CGFloat width01 = cutImagewidth;
    CGFloat scale = MIN(cutImage.size.width / DK_SCREEN_W, cutImage.size.height / DK_SCREEN_H);
    CGFloat clipWidht = width01 * scale;
    CGFloat clipHeight = cutImageheight* scale ;
    CGRect cropFrame = CGRectMake((cutImage.size.width - clipWidht) * 0.5, (cutImage.size.height - clipHeight) * 0.5, clipWidht, clipHeight);
    CGFloat orgX = cropFrame.origin.x * (cutImage.size.width / imageView.frame.size.width);
    CGFloat orgY = cropFrame.origin.y * (cutImage.size.height / imageView.frame.size.height);
    CGFloat width = cropFrame.size.width * (cutImage.size.width / imageView.frame.size.width);
    CGFloat height = cropFrame.size.height * (cutImage.size.height / imageView.frame.size.height);
    CGRect cropRect = CGRectMake(orgX, orgY, width, height);
    CGImageRef imgRef = CGImageCreateWithImageInRect(cutImage.CGImage, cropRect);
    CGFloat deviceScale = [UIScreen mainScreen].scale;
    UIGraphicsBeginImageContextWithOptions(cropFrame.size, 0, deviceScale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, cropFrame.size.height);
    CGContextScaleCTM(context, 1, -1);
    CGContextDrawImage(context, CGRectMake(0, 0, cropFrame.size.width, cropFrame.size.height), imgRef);
    UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
    CGImageRelease(imgRef);
    UIGraphicsEndImageContext();
    return newImg;
}

#pragma mark - private methods
/// 查看相机权限
- (void)checkCameraAccessWithBlock:(void(^)(BOOL cameraAvailable))handler{
    
    // 检测相机设备是否可用
    BOOL cameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if (!cameraAvailable) {
        if (handler) {
            handler(NO);
        }
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"相机设备不可用" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            // 取消
            [self closeCarema];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (authStatus == AVAuthorizationStatusDenied) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NoCameraAccessAlertTitle message:NoCameraAccessAlertMessage preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            // 取消
            [self closeCarema];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 去设置
            NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
                [[UIApplication sharedApplication] openURL:settingURL options:@{} completionHandler:^(BOOL success) {
                    // 成功进入设置
                }];
            }
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        
        if (handler) {
            handler(NO);
        }
    }
    else if (authStatus == AVAuthorizationStatusNotDetermined)
    {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                dispatch_async(dispatch_get_main_queue(), ^{
                   // 用户授权
                    if (handler) {
                        handler(YES);
                    }
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                   // 用户拒绝
                    if (handler) {
                        handler(NO);
                    }
                    [self closeCarema];
                });
            }
        }];
    }else
    {
        // 用户授权
        if (handler) {
            handler(YES);
        }
    }
}
@end
